//
//  APBLEDevice.m
//  FuweiCloud
//
//  Created by michael on 2024/4/29.
//

#import "APBLEDevice.h"
#import "APBLEParameter.h"
#import <CoreBluetooth/CBAdvertisementData.h>
#import "NSData+VLExtension.h"
#import "FWLogger.h"

@interface APBLEDevice ()
@property (nonatomic, strong) CBPeripheral *peripheral;

///< 设备名称
@property (nonatomic, copy) NSString *name;

///< 设备mac地址
@property (nonatomic, copy) NSString *mac;
@property (nonatomic, copy) NSString *mac_format;

///< 设备是否绑定
@property (nonatomic, assign) BOOL binded;

@property (nonatomic, assign) APBLEDeviceMatchType match_num;
@property (nonatomic, assign) NSInteger manufaturer_id;

@end

@implementation APBLEDevice

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"peripheral"];
}

- (instancetype)initWithAdvertisementData:(NSDictionary *)advData peripheral:(CBPeripheral *)peripheral prefixes:(nonnull NSArray<NSString *> *)prefixes {
    if (self = [super init]) {
        _peripheral = peripheral;
        ///< 设备名称
        _name = advData[CBAdvertisementDataLocalNameKey];
        ///< 厂商数据
        NSData *mfrData = advData[CBAdvertisementDataManufacturerDataKey];
        _match_num = 0;
        if ([_name isEqualToString:@"arlf_SE60"]) {
            _match_num = APBLEDeviceMatchTypeD288;
            uint8_t bind = 0;
            if (mfrData.length) {
                [mfrData getBytes:&bind range:NSMakeRange(0, 1)];
            }
            _binded = bind == 0x80;
            if (advData[CBAdvertisementDataServiceDataKey]) {
                NSData *serData = ((NSDictionary *)advData[CBAdvertisementDataServiceDataKey]).allValues.firstObject;
                DDLogInfo(@"🔵: bleADV name:%@, mfrData:%@, serviceData:%@",_name,mfrData.vl_hex,serData.vl_hex);
                _mac = [serData subdataWithRange:NSMakeRange(1, serData.length-1)].vl_hex.lowercaseString;
            }
        }else if ([prefixes indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
            return [_name hasPrefix:obj];
        }] != NSNotFound) {
            DDLogInfo(@"🔵: bleADV name:%@, mfrData:%@, serviceData:NULL",_name,mfrData.vl_hex);
            _mac = [[_name substringFromIndex:4] lowercaseString];
            if (mfrData.length != 7) { ///< 旧款AL501蓝牙广播没有写入没有厂商信息
                _match_num = APBLEDeviceMatchTypeAL501;
            } else {
                int8_t mfrId; ///< 厂商ID，一般为1
                [mfrData getBytes:&mfrId range:NSMakeRange(2, 1)];
                uint8_t bind; ///< 设备绑定状态1个字节
                [mfrData getBytes:&bind range:NSMakeRange(3, 1)];
                uint16_t matchId; ///< 设备型号
                [mfrData getBytes:&matchId range:NSMakeRange(5, 2)];
                matchId = CFSwapInt16HostToBig(matchId);
                _manufaturer_id = mfrId;
                _match_num = matchId;
                _binded = bind > 0;
            }
        }
        if (_mac.length == 12) {
            _mac_format = @"";
            for (int i = 0; i < _mac.length; i+=2) {
                _mac_format = [_mac_format stringByAppendingFormat:@"%@%@",[_mac substringWithRange:NSMakeRange(i, 2)].uppercaseString,(i==(_mac.length-2))?@"":@":"];
            }
        }else {
            DDLogInfo(@"🔵: 广播信息错误：%@",_mac);
        }
        DDLogInfo(@"🔵: 设备名称：%@",_name);
        DDLogInfo(@"🔵: 设备MAC地址：%@",_mac);
        DDLogInfo(@"🔵: 设备绑定状态：%d",_binded);
        DDLogInfo(@"🔵: 设备配对值：%ld",_match_num);
    }
    return self;
}

- (void)dealloc {
    NSLog(@"[device:%@ dealloc]",self.mac);
}

@end
